/*
 * Universidade Federal Fluminense
 * Instituto de Computação
 * Prof. Pedro Braconnot Velloso
 * Sistemas Distribuídos - Turma 2011/2
 * Author: Gabriel Almeida de Oliveira
 * Description: Client Side for testing and learning purposes
 */


#include "client.h"

//Socket-Specific Libraries



void client(void *thread_args){
	packet *curr;
	struct sockaddr_in clientAddress, serverAddress;
	struct hostent *host;
	char errorString[140], msg[MAX_MSG_SIZE], *hostname;
	int sock, n;
	
	// get arguments from struct
	struct arguments *my_args = (struct arguments *) thread_args;
	curr = my_args->peer_list;
	hostname = my_args->hostname;	
	
	//check if server exists and is valid
  	host = gethostbyname(hostname);
  	if(host==NULL) {
    	printf("Client: unknown host '%s' \n", hostname);
    	exit(ERROR_INVALID_HOST);
  	}

	printf("Sending data to '%s' (IP : %s) using TCP port %d \n", host->h_name, inet_ntoa( *(struct in_addr *) host->h_addr_list[0]), DEFAULT_PORT );

	//build serverAddress structure
	serverAddress.sin_family = host->h_addrtype;
	memcpy((char *) &serverAddress.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
	serverAddress.sin_port = htons(DEFAULT_PORT);

	
	if( (sock = socket(AF_INET,SOCK_STREAM,0) )< 0){
		snprintf(errorString, sizeof(errorString), "Cannot open socket");
		DieWithError(errorString);
	}
	    
    //Try to connect to the server using the variable &serverAddress
     
    
    if ( (connect(sock, (struct sockaddr *)&serverAddress, sizeof (serverAddress) ) ) < 0 )
    {
    	snprintf (errorString, sizeof(errorString), "Client: Connection error");
		DieWithError(errorString);
    }
    
	//Send data: msg and level
	sprintf(msg, "%d;%s;%s", curr->level, curr->msg, inet_ntoa(curr->address.sin_addr));
	
	if( (n = write(sock, msg, strlen(msg) ) ) < 0 ) {
		snprintf (errorString, sizeof(errorString), "Client: cannot send data");
		DieWithError(errorString);
	} else printf("Client: Message sent: %s with level %d\n\n", curr->msg, curr->level);		
	close(sock);
}
